package com.ymatou.apigateway.testcase;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.apigateway.parameter.AesUtil;
import com.ymatou.apigateway.parameter.GetSqOrderPaymentInfoReq;
import com.ymatou.apigateway.parameter.OpenapiReq;
import com.ymatou.apigateway.parameter.pojo.ProductForGetSqOrderPaymentInfo;
import com.ymatou.apigateway.service.OpenapiService;
import com.ymatou.apigateway.service.ShenqiGetOrderListCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.database.model.Application;
import com.ymttest.database.model.AuthCode;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailPo;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailSubPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sharding.db.sqlwapper.OrderWapper;
import com.ymttest.database.sqlwapper.OpenApiWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class Ts_SqGetOrderPaymentInfo {

	private static OpenapiReq openapiReq;
	private static ShenqiGetOrderListCall shenqiGetOrderListCall;
	private static OpenApiWapper openApiWapper;
	private static GetSqOrderPaymentInfoReq getSqOrderPaymentInfoReq;
	
	private static OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
	private static OrderWapper orderWapper = new OrderWapper();
	
	private static YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
	
	private static long autotest_goodsOwnerId = Long.valueOf(EnvSetup
			.getData("autotest_goodsOwnerId")); 

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("openapi获取神器支付单详情");
		openApiWapper = new OpenApiWapper();
	}

	@Before
	public void caseUp() {

		openapiReq = new OpenapiReq();
		getSqOrderPaymentInfoReq = new GetSqOrderPaymentInfoReq();
		shenqiGetOrderListCall = new ShenqiGetOrderListCall();
		openapiReq.setMethod("sq.order.info2customs.get");

	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(shenqiGetOrderListCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	public void verify(long orderId) throws Exception {

		List<OrderDetailPo> orderDetailPos = orderShardingWapper
				.selectOrderDetailbyOrderId(orderId);

		JSONArray actualList = shenqiGetOrderListCall.getContent()
				.getJSONObject("payment_info").getJSONArray("products");

		ArrayList<ProductForGetSqOrderPaymentInfo> productForGetSqOrderPaymentInfos = new ArrayList<>();

		for (OrderDetailPo orderDetailPo : orderDetailPos) {

			if (orderDetailPo.getSubProduct()) {

				List<OrderDetailSubPo> orderDetailSubPos = orderShardingWapper
						.selectOrderDetailSubByDetailId(orderDetailPo
								.getOrderDetailId());

				for (OrderDetailSubPo orderDetailSubPo : orderDetailSubPos) {

					ProductForGetSqOrderPaymentInfo productForGetSqOrderPaymentInfo = new ProductForGetSqOrderPaymentInfo();

					String skuId = orderDetailSubPo.getSubCatalogId();
					String outerSkuId = orderDetailSubPo.getSku();
					String productId = ymtCatalogsIWapper
							.selectCatalogsByCatalogId(skuId).getsProductId();

					productForGetSqOrderPaymentInfo.setOuter_sku_id(outerSkuId);
					productForGetSqOrderPaymentInfo.setProduct_id(productId);
					productForGetSqOrderPaymentInfo.setSku_id(skuId);

					productForGetSqOrderPaymentInfos
							.add(productForGetSqOrderPaymentInfo);
				}
			} else {

				ProductForGetSqOrderPaymentInfo productForGetSqOrderPaymentInfo = new ProductForGetSqOrderPaymentInfo();

				String skuId = orderDetailPo.getCatalogId();
				String productId = orderDetailPo.getProductId();
				String outerSkuId = orderWapper.selectOrderDetailExtByOrderId(
						orderDetailPo.getOrderDetailId()).getSku();

				productForGetSqOrderPaymentInfo.setOuter_sku_id(outerSkuId);
				productForGetSqOrderPaymentInfo.setProduct_id(productId);
				productForGetSqOrderPaymentInfo.setSku_id(skuId);

				productForGetSqOrderPaymentInfos
						.add(productForGetSqOrderPaymentInfo);
			}
		}

		for (int i = 0; i < actualList.length(); i++) {

			JSONObject actualObject = actualList.getJSONObject(i);
			ProductForGetSqOrderPaymentInfo productForGetSqOrderPaymentInfo = productForGetSqOrderPaymentInfos
					.get(i);

			String skuId = productForGetSqOrderPaymentInfo.getSku_id();
			String productId = productForGetSqOrderPaymentInfo.getProduct_id();
			String outerSkuId = productForGetSqOrderPaymentInfo
					.getOuter_sku_id();

			Logger.verifyEquals(outerSkuId,
					actualObject.getString("outer_sku_id"), "验证outer_sku_id");
			Logger.verifyEquals(productId,
					actualObject.getString("product_id"), "验证product_id");
			Logger.verifyEquals(skuId, actualObject.getString("sku_id"),
					"验证sku_id");
		}
	}

	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_GetSqOrderPaymentInfo_001() {
		Logger.start(true, "openapi店主获取支付单详情 指定orderid");
		try {
			
//			AgentProductBean productBean = DGSQBuildProxyChainCallService
//					.createProxychain((int) autotest_goodsOwnerId, 0, false,
//							false);
//
//			TradingServiceResp placeOrderResp = TradingForDGSQCallService
//					.placeOrder1(productBean, autotest_goodsOwnerId);
//
//			Order order = placeOrderResp.getOrderList().get(0);
//
//			long sellerId = order.getSellerId();
//			Long userId = placeOrderResp.getUserId();
//
//			long orderId = order.getOrderId();
//
//			BigDecimal amount = placeOrderResp.getPayableAmount();
//
//			// 支付订单
//			Long thirdTradingId = TradingForDGSQCallService.payOrder(userId,
//					placeOrderResp.getTradingId());
//
//			// 支付网关支付回调交易
//			SQPayGateWayCallService.DGSQNotifyCall(
//					String.valueOf(thirdTradingId),
//					amount.subtract(BigDecimal.ZERO).toString(),
//					userId.intValue(), BigDecimal.ZERO.toPlainString());
//
//			Thread.sleep(5000);
			
			long orderId = 13236908699L;
			long sellerId = autotest_goodsOwnerId;

			getSqOrderPaymentInfoReq.setOrder_id(orderId);

			Application application = openApiWapper
					.selectApplicationBySellerId(sellerId).get(0);

			String app_id = application.getApp_id();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);

			String app_secret = application.getApp_secret();

			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(getSqOrderPaymentInfoReq));
			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.order.info2customs.get",
							app_id);

			shenqiGetOrderListCall.setUrl(url);

			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			shenqiGetOrderListCall.setData(openapiReq);

			shenqiGetOrderListCall.callService();

			Logger.verifyEquals("0000", shenqiGetOrderListCall.getCode(), 
					"校验code");
			Logger.verifyEquals("", shenqiGetOrderListCall.getMsg(),
					"校验message");

			Logger.verifyNotNull(shenqiGetOrderListCall.getContent(),
					"校验content");
			
			this.verify(orderId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_GetSqOrderPaymentInfo_002() {
		Logger.start(true, "openapi店主获取组合商品支付单详情 指定orderid");
		try {
			
//			AgentProductBean productBean = DGSQBuildProxyChainCallService
//					.createComposeProductProxychain((int)autotest_goodsOwnerId, false);
//
//			TradingServiceResp placeOrderResp = TradingForDGSQCallService
//					.placeComposeProductOrder(productBean, (int)autotest_goodsOwnerId);
//
//			Order order = placeOrderResp.getOrderList().get(0);
//
//			long sellerId = order.getSellerId();
//			Long userId = placeOrderResp.getUserId();
//
//			long orderId = order.getOrderId();
//
//			BigDecimal amount = placeOrderResp.getPayableAmount();
//
//			// 支付订单
//			Long thirdTradingId = TradingForDGSQCallService.payOrder(userId,
//					placeOrderResp.getTradingId());
//
//			// 支付网关支付回调交易
//			SQPayGateWayCallService.DGSQNotifyCall(
//					String.valueOf(thirdTradingId),
//					amount.subtract(BigDecimal.ZERO).toString(),
//					userId.intValue(), BigDecimal.ZERO.toPlainString());
//
//			Thread.sleep(5000);
			
			long orderId = 13241388699L;
			long sellerId = autotest_goodsOwnerId;

			getSqOrderPaymentInfoReq.setOrder_id(orderId);

			Application application = openApiWapper
					.selectApplicationBySellerId(sellerId).get(0);

			String app_id = application.getApp_id();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);

			String app_secret = application.getApp_secret();

			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(getSqOrderPaymentInfoReq));
			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.order.info2customs.get",
							app_id);

			shenqiGetOrderListCall.setUrl(url);

			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			shenqiGetOrderListCall.setData(openapiReq);

			shenqiGetOrderListCall.callService();

			Logger.verifyEquals("0000", shenqiGetOrderListCall.getCode(), 
					"校验code");
			Logger.verifyEquals("", shenqiGetOrderListCall.getMsg(),
					"校验message");

			Logger.verifyNotNull(shenqiGetOrderListCall.getContent(),
					"校验content");

			this.verify(orderId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	public static void main(String[] args) {
		
//		Ts_GetSqOrderPaymentInfo test = new Ts_GetSqOrderPaymentInfo();
//		test.Tc_sqgetorderlist_008();
	}
}
